<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Name_FormItem" prop="Name" label="名称">
							<el-input v-model="searchData.Name" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="ClassName_FormItem" prop="ClassName" label="类名">
							<el-input v-model="searchData.ClassName" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="TaskType_FormItem" prop="TaskType" label="任务类型">
							<el-select v-model="searchData.TaskType" clearable>
								<el-option key="单次任务" value="单次任务" label="单次任务"></el-option>
								<el-option key="周期任务" value="周期任务" label="周期任务"></el-option>
								<el-option key="定时任务" value="定时任务" label="定时任务"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="LastRunResult_FormItem" prop="LastRunResult" label="上次运行状态">
							<el-select v-model="searchData.LastRunResult" clearable>
								<el-option key="初始化" value="初始化" label="初始化"></el-option>
								<el-option key="失败" value="失败" label="失败"></el-option>
								<el-option key="成功" value="成功" label="成功"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 高级搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Description_FormItem" prop="Description" label="描述">
								<el-input v-model="searchData.Description" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="StartTime_FormItem" prop="StartTime" label="上次运行开始时间">
								<el-date-picker type="daterange" v-model="searchData.StartTime" clearable style="width: 100%"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="EndTime_FormItem" prop="EndTime" label="上次运行结束时间">
								<el-date-picker type="daterange" v-model="searchData.EndTime" clearable style="width: 100%"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Repeat_FormItem" prop="Repeat" label="重复次数">
								<el-input-number v-model="searchData.Repeat" clearable style="width: 100%"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IsForever_FormItem" prop="IsForever" label="是否永久重复">
								<el-select v-model="searchData.IsForever" clearable>
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IntervalInSeconds_FormItem" prop="IntervalInSeconds" label="间隔秒数">
								<el-input-number v-model="searchData.IntervalInSeconds" clearable style="width: 100%"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="DelaySeconds_FormItem" prop="DelaySeconds" label="延迟秒数">
								<el-input-number v-model="searchData.DelaySeconds" clearable style="width: 100%"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="LastRunTime_FormItem" prop="LastRunTime" label="上次运行时长">
								<el-input-number v-model="searchData.LastRunTime" clearable style="width: 100%"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Cron_FormItem" prop="Cron" label="Cron表达式">
								<el-input v-model="searchData.Cron" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IsEnable_FormItem" prop="IsEnable" label="是否启用">
								<el-select v-model="searchData.IsEnable" clearable>
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IsRun_FormItem" prop="IsRun" label="是否运行">
								<el-select v-model="searchData.IsRun" clearable>
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="CreateTime_FormItem" prop="CreateTime" label="创建时间">
								<el-date-picker type="daterange" v-model="searchData.CreateTime" clearable style="width: 100%"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="UpdateTime_FormItem" prop="UpdateTime" label="更新时间">
								<el-date-picker v-model="searchData.UpdateTime" clearable style="width: 100%"></el-date-picker>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysTaskV2/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysTaskV2/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysTaskV2/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysTaskV2/SysTaskV2ExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysTaskV2/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysTaskV2/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysTaskV2/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="调度任务;true;HengTong.Areas._Admin.Controllers;SysTaskV2">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysTaskV2Api as api } from '/@/views/_admin/systaskv2/api';
import { ISysTaskV2View, ISysTaskV2Query } from '/@/views/_admin/systaskv2/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysTaskV2Query;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({});

const searchData = ref<ISysTaskV2Query>({
	Name: null,
	ClassName: null,
	Description: null,
	TaskType: null,
	StartTime: null,
	EndTime: null,
	Repeat: null,
	IsForever: null,
	IntervalInSeconds: null,
	DelaySeconds: null,
	LastRunTime: null,
	Cron: null,
	LastRunResult: null,
	IsEnable: null,
	IsRun: null,
	CreateTime: null,
	UpdateTime: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '名称', key: 'Name', type: 'text', isCheck: true },
		{ title: '类名', key: 'ClassName', type: 'text', isCheck: true },
		{ title: '描述', key: 'Description', type: 'text', isCheck: true },
		{ title: '任务类型', key: 'TaskType', type: 'text', isCheck: true },
		{ title: '上次运行开始时间', key: 'StartTime', type: 'text', isCheck: true },
		{ title: '上次运行结束时间', key: 'EndTime', type: 'text', isCheck: true },
		{ title: '重复次数', key: 'Repeat', type: 'text', isCheck: true },
		{ title: '是否永久重复', key: 'IsForever', type: 'switch', isCheck: true },
		{ title: '延迟秒数', key: 'IntervalInSeconds', type: 'text', isCheck: true },
		{ title: '延迟秒数', key: 'DelaySeconds', type: 'text', isCheck: true },
		{ title: '上次运行时长', key: 'LastRunTime', type: 'text', isCheck: true },
		{ title: 'Cron表达式', key: 'Cron', type: 'text', isCheck: true },
		{ title: '上次运行状态', key: 'LastRunResult', type: 'text', isCheck: true },
		{ title: '是否启用', key: 'IsEnable', type: 'switch', isCheck: true },
		{ title: '是否运行', key: 'IsRun', type: 'switch', isCheck: true },
		{ title: 'CreateTime', key: 'CreateTime', type: 'text', isCheck: true },
		{ title: 'UpdateTime', key: 'UpdateTime', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysTaskV2View) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysTaskV2View) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysTaskV2View) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysTaskV2View) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [getTableData()];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
